(function($) {
    // 等待DOM完全加载
    $(document).ready(function() {
        console.log("Document ready, initializing score calculation...");

        // 获取所有分数和数量输入框
        const scoreInputs = [
            'single_choice_score',
            'multiple_choice_score',
            'judgment_score'
        ];
        const countInputs = [
            'single_choice_count',
            'multiple_choice_count',
            'judgment_count'
        ];

        // 检查必要的字段是否存在
        function checkFields() {
            let missingFields = [];
            scoreInputs.concat(countInputs).forEach(function(fieldName) {
                if ($('#id_' + fieldName).length === 0) {
                    missingFields.push(fieldName);
                }
            });
            if ($('#id_total_score').length === 0) {
                missingFields.push('total_score');
            }
            if (missingFields.length > 0) {
                console.error("Missing fields:", missingFields);
                return false;
            }
            return true;
        }

        // 计算总分的函数
        function calculateTotalScore() {
            console.log("Calculating total score...");
            let totalScore = 0;
            for (let i = 0; i < scoreInputs.length; i++) {
                const scoreField = $('#id_' + scoreInputs[i]);
                const countField = $('#id_' + countInputs[i]);
                if (scoreField.length && countField.length) {
                    const score = parseFloat(scoreField.val()) || 0;
                    const count = parseInt(countField.val()) || 0;
                    totalScore += score * count;
                    console.log(`${scoreInputs[i]}: ${score} * ${count} = ${score * count}`);
                } else {
                    console.warn(`Field not found: ${scoreInputs[i]} or ${countInputs[i]}`);
                }
            }

            // 更新总分显示
            const totalScoreField = $('#id_total_score');
            if (totalScoreField.length) {
                totalScoreField.val(totalScore.toFixed(2));
                console.log(`Total score updated: ${totalScore.toFixed(2)}`);
                // 添加一个视觉反馈
                totalScoreField.css('background-color', '#e8f0fe');
                setTimeout(function() {
                    totalScoreField.css('background-color', '');
                }, 500);
            } else {
                console.error("Total score field not found");
            }
        }

        // 为所有输入框添加事件监听器
        function addEventListeners() {
            scoreInputs.concat(countInputs).forEach(function(fieldName) {
                const field = $('#id_' + fieldName);
                if (field.length) {
                    field.on('input change', calculateTotalScore);
                    console.log(`Event listener added to ${fieldName}`);
                } else {
                    console.warn(`Field not found: ${fieldName}`);
                }
            });
        }

        // 确保表单字段有正确的ID
        function ensureTotalScoreField() {
            const totalScoreField = $('.field-total_score input');
            if (totalScoreField.length) {
                totalScoreField.attr('id', 'id_total_score').attr('readonly', true);
                console.log("Total score field ID set and made readonly");
            } else {
                console.error("Total score field not found in the form");
            }
        }

        // 初始化函数
        function initScoreCalculation() {
            if (checkFields()) {
                addEventListeners();
                ensureTotalScoreField();
                calculateTotalScore();
                console.log("Score calculation initialized successfully");
            } else {
                console.error("Failed to initialize score calculation due to missing fields");
            }
        }

        // 运行初始化
        initScoreCalculation();

        // 在Django admin的popup窗口关闭时重新计算总分
        if (window.dismissAddAnotherPopup) {
            const originalDismissAddAnotherPopup = window.dismissAddAnotherPopup;
            window.dismissAddAnotherPopup = function(win, newId, newRepr) {
                originalDismissAddAnotherPopup(win, newId, newRepr);
                calculateTotalScore();
                console.log("Total score recalculated after popup dismissed");
            };
        }
    });
})(django.jQuery);